<!--文章列表组件 -->
<template>
  <div class="article-list" ref="articlelist" @scroll="scrollFn">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onload()"
      >
        <article-item v-for="item in articles" :key="item.art_id" :article="item"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from './article-item.vue'
import { getArticles } from '@/api/articles'

export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  data () {
    return {
      loading: false, // 加载中状态
      finished: false, // 是否完全加载
      error: false, // 是否加载失败
      articles: [], // 文章列表
      refreshing: false, // 正在刷新
      timestamp: Date.now() // 事件戳，调接口传入的参数
      // scrollTop: 0 // 阅读位置

    }
  },
  props: {
    articleId: {
      type: Number,
      default: 0

    }
  }, // 接收首页传的数据
  methods: {
    // 上拉加载事件
    async onload () {
      const res = await getArticles(this.articleId, this.timestamp)
      // console.log(res)
      this.articles.push(...res[1].data.results)
      if (res[1].data.pre_timestamp) {
        this.timestamp = res[1].data.pre_timestamp
      } else {
        this.finished = true
      }
      this.loading = false
    },
    // 下滑刷新事件
    async onRefresh () {
      const res = await getArticles(this.articleId, Date.now()) // 调用新闻推荐接口
      this.articles = res[1].data.results // 更新文章列表
      this.timestamp = res[1].data.pre_timestamp // 更新时间戳
      this.finished = false // 重置完成加载状态，可以再次加载更多
      this.$toast.success('刷新成功')
      console.log(this.articles)
      this.refreshing = false // 关闭顶部加载中
    },
    // 监听滚动事件
    scrollFn () {
      this.scrollTop = this.$refs.articlelist.scrollTop // 记录滚动位置
    }
  },
  // 激活组件钩子 ,进入组件时还原滚动位置
  activated () {
    this.$refs.articlelist.scrollTop = this.scrollTop
  }
}

</script>

  <style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
